package com.etc.util;

import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author kalista
 * @Description 地图相关操作得工具类  -》 高得地图api
 * @Date 2021/5/25  10:18
 **/
public class MapUtil {

    // 定义高得地图开发者key
    private static String key = "ba1539fb52a33d97d645b9692d5fa4b8";

    /**
     * 获取城市县级市
     *
     * @param districtsName 城市名字
     */
    public static JSONArray getDistricts(String districtsName) {
//        https://restapi.amap.com/v3/config/district?keywords=北京&subdistrict=2&key=<用户的key>
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&keywords=" + districtsName).append("&subdistrict=1").append("&extensions=all");
        String res = HttpUtil.get("https://restapi.amap.com/v3/config/district?" + s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        return jsonObject.getJSONArray("districts");
    }

    /**
     * 解析json数据返回我们要得地区得对象
     *
     * @param districts
     * @return
     */
    public static void parseDistrictInfo(JSONArray districts, String targeCitycode, List<District> districtList) {


        Iterator<Object> iterator = districts.iterator();
        while (iterator.hasNext()) {
            JSONObject jo = (JSONObject) iterator.next();


            /**
             *       "citycode":"0351",
             *             "adcode":"140100",
             *             "name":"太原市",
             *             "center":"112.549248,37.857014",
             *             "level":"city",
             */
            String citycode = jo.getString("citycode");
            String name = jo.getString("name");
            String level = jo.getString("level");
            String polyline = jo.getString("polyline");

            // 城市
            if (level.equals("city")) {
                JSONArray districts1 = jo.getJSONArray("districts");
                parseDistrictInfo(districts1, null, districtList);
            } else if (level.equals("district")) {
                if (null != targeCitycode && targeCitycode.equals(citycode)) {
                    District district = new District(citycode, name, polyline);
                    districtList.add(district);
                }
                if (null == polyline) {
                    // 如果这个值没有就再次发送请求获取 边界
                    JSONArray districts1 = getDistricts(name);
                    parseDistrictInfo(districts1, citycode, districtList);
                }
                continue;
            }
        }
    }


    public static void main(String[] args) {
        List<District> districtList = new ArrayList<>();
        JSONArray res = getDistricts("天津");
        parseDistrictInfo(res, null, districtList);
        for (District re : districtList) {
            System.out.println(re.toString());
        }

    }


}
